/**
* Description: 批量创建
*
* Created by hrx on 2023/10/8
*/
<template>
  <div class="upload-file-dialog">
    <el-dialog
      :title="title"
      v-model="dialogFormVisible"
      width="660px"
      :close-on-click-modal="false"
    >
      <div class="contents">
        <div class="contentItem">
          <h3>第一步：下载导入模板</h3>
          <el-button link @click="downLoadDemo">下载excel模板</el-button>
        </div>
        <div class="contentItem">
          <h3>第二步：上传excel文件</h3>
        </div>
        <div class="contentItem" style="justify-content: center">
          <el-upload
            class="upload-demo"
            style="width: 360px"
            drag
            :headers="headers"
            action="/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="handleUpload"
            accept=".xlsx, .xls"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text" style="color: #778ca2">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                <p v-if="!errorData.show" style="color: rgb(119, 140, 162);margin-top: 20px" >上传文件支持格式：xlsx、xls；文件上限5MB</p>
                <p v-if="errorData.show" class="errors">
                  <span style="margin-right: 20px">{{ errorData.fileName }}</span>
                  <span v-if="errorData.type == 'success'">成功</span>
                  <span v-if="errorData.type == 'error'">失败</span>
                  <i
                    v-if="errorData.type == 'success'"
                    class="el-icon-check elIcon"
                  ></i>
                  <i
                    v-if="errorData.type == 'error'"
                    class="el-icon-close elIcon bgRed"
                  ></i>
                  <a
                    v-if="errorData.type == 'error'"
                    class="mainColor"
                    style="text-decoration: none; cursor: pointer"
                    @click="downLoadFileFun(errorData)"
                  >下载</a
                  >
                </p>
              </div>
            </template>
          </el-upload>
        </div>
        <slot>
          <div class="contentItems">
            <h3>批量创建设备说明</h3>
            <p>1、上传前请先下载模板，按照模板要求内容录入到模板中。</p>
            <p>2、设备编号不可重复</p>
          </div>
        </slot>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible = false">关 闭</el-button>
        </span>
      </template>

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {downloadFile, saveAs} from "@/utils/download";
import {ElMessage, UploadFile, UploadFiles, UploadRawFile, UploadRequestOptions} from "element-plus";
import {AxiosResponse} from "axios";
import {IResponseDto} from "@/utils/ajax";
interface Prop{
  demoUrl: string | undefined,
  title: string,
  uploadApi: (params: any) => Promise<AxiosResponse<IResponseDto>>
}

const prop = withDefaults(defineProps<Prop>(), {
  title: '',
  demoUrl: '',
})

interface errorVO {
  show: boolean,
  type: string,
  file: string,
  fileName: string,
  url: string,
}

const emit = defineEmits(['afterSubmit']);

const dialogFormVisible = ref<boolean>(false);

const errorData = reactive<errorVO>({
  show: false,
  type: "success",
  file: "",
  fileName: "",
  url: ""
})

const headers = reactive({
    Authorization: window.localStorage.getItem("trainToken"),
    merchantCode: "1",
})

const downLoadDemo = () => {
  saveAs(prop.demoUrl, 'test')
}

const handleAvatarSuccess = (response: AxiosResponse<IResponseDto>, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  if (response.data.code == 0) {
    ElMessage.success("导入成功");
    errorData.type = "success";
    emit('afterSubmit', '');
  } else {
    errorData.type = "error";
    // this.errorData.show = true;
    errorData.file = response.data.msg;
  }
}
const beforeAvatarUpload = (file: UploadRawFile) => {
  const isJPG = file.type.indexOf("sheet") !== -1;
  const isLt5M = file.size / 1024 / 1024 < 5;
  errorData.fileName = file.name;
  if (!isJPG) {
    ElMessage.error("导入文件格式错误，请更正后再导入!");
    return isJPG;
  }
  if (!isLt5M) {
    ElMessage.error("导入文件文件超过5MB，请更正后再导入!");
    return isLt5M;
  }
  return true;
}
const handleUpload = (file: UploadRequestOptions)  => {
  const formData = new FormData();
  formData.append('file', file.file);
  return prop.uploadApi(formData);
}
const downLoadFileFun = (err: errorVO) => {
  downloadFile(err.url, "导入题目模板-导入失败.xlsx");
}


defineExpose({
  dialogFormVisible
})
</script>

<style lang="scss" scoped>
.upload-file-dialog {
  :deep(.el-dialog__body) {
    padding: 20px !important;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
    min-height: 550px;
    max-height: 550px;
    overflow: auto;
  }
  .contents {
    .contentItem {
      margin-bottom: 30px;
      .is-link{
        color: $theme-color;
      }
      h3 {
        font-size: 14px;
        font-weight: 700;
        color: #252631;
        margin-right: 30px;
      }
      display: flex;
      align-items: center;
      .errors {
        display: flex;
        span {
          margin-right: 10px;
        }
      }
      .elIcon {
        width: 16px;
        height: 16px;
        font-size: 14px;
        color: #fff;
        text-align: center;
        line-height: 16px;
        display: block;
        background: #23bcca;
        border-radius: 50%;
        margin-right: 20px;
      }
      .bgRed {
        background: $auxiliary-color-pink;
      }
    }
    .contentItems {
      h3 {
        font-size: 14px;
        font-weight: 700;
        margin-bottom: 10px;
      }
      p {
        font-size: 14px;
      }
    }
  }
}
</style>